package hackthon.controller;

import hackthon.core.Constant;
import hackthon.core.MyCookie;
import hackthon.service.AttendService;
import hackthon.service.RegisterService;
import hackthon.service.SendEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wuwenhao on 15/1/8.
 */

@Controller
public class SendEmail {

    @Autowired
    public SendEmailService sendEmailService;

    @Autowired
    public AttendService attendService;

    @Autowired
    public RegisterService registerService;

    @RequestMapping("/sendEmail")
    public String index(HttpServletRequest request, HttpServletResponse response){
        Cookie cookie = MyCookie.getCookie(Constant.LOGIN_COOKIE_NAME,request);
        String username = Constant.getCurrentUser(cookie);
        String subject = request.getParameter("subject");
        String toAddress = request.getParameter("toAddress");
        String content = request.getParameter("content");
        String date = request.getParameter("date");
        String place = request.getParameter("place");
        int attendMax = Integer.parseInt(request.getParameter("attendMax"));
        int attendId = attendService.insertAttend(toAddress);

        int emailId = sendEmailService.storeEmailToDB(username,subject,content, date,place,attendId, attendMax, attendMax+5);
        registerService.initRegister(emailId, toAddress);

        if(sendEmailService.sendEmail(username,subject,content,toAddress,date,emailId)){
            return "Test";
        }
        return null;
    }
}
